<?php
namespace App\Logic\ZiNiao\Work;

use App\Logic\ZiNiao\Api\Tasks;
use App\Models\ZiNiao\PlansPost;
use App\Models\ZiNiao\PlansTasks as PlansTasksModel;
class PlansTasks
{
    public static function exeInit($planId = 0){
        $query = PlansPost::query()->where('status',0);
        if($planId){
            $query->where('planId' , $planId);
        }
        $res = $query->get();
        foreach ($res as $re){
            $status = self::_exe($re->planId);
            $re->status = $status;
            $re->save();
        }
    }

    public static function exe($planId = 0){
        $query = PlansTasksModel::query()
            ->where('planStatus','ENABLED')
            ->where('taskStatus','RUNNING');
        if($planId){
            $query->where('planId' , $planId);
        }
        $res = $query->get();
        foreach ($res as $re){
            self::_exe($re->planId);
        }
    }

    private static function _exe($planId)
    {
        $example = new Tasks();
        $pageNum = 1;
        $pageSize = 500;
        $bizContent = [
            "planId" => $planId,
            "pageNum" => $pageNum,
            "pageSize" => $pageSize,
        ];
        $data = $example->exe($bizContent);
        if(!$data)return 0;
        self::_parseData($data);
        $pageTotal = intval(ceil($data->totalCount / $pageSize));
        while (true){
            if($pageNum == $pageTotal)break;
            $pageNum++;
            $_bizContent = [
                "planId" => $planId,
                "pageNum" => $pageNum,
                "pageSize" => $pageSize,
            ];
            $_data = $example->exe($_bizContent);
            if(!$_data)continue;
            self::_parseData($_data);
        }
        return 1;
    }

    private static function _parseData($data){
        foreach ($data->curPage as $_curPage){
            PlansTasksModel::query()->updateOrCreate(
                [
                    'planId' => $_curPage->planId,
                    'taskId' => $_curPage->taskId,
                ],
                [
                    'planStatus' => $_curPage->planStatus,
                    'taskStatus' => $_curPage->taskStatus,
                    'cost' => $_curPage->cost,
                    'runCount' => $_curPage->runCount,
                    'outPutCount' => $_curPage->outPutCount,
                ]
            );
        }
    }
}
